﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace System.Windows.Controls.WpfPropertyGrid
{
    public class RelayCommand : ICommand
    {


        public RelayCommand(string text, string name)
        {
            Name = name;
            Text = text;
        }


        public string Text { get; set; }
        public string Name { get; set; }


        public bool CanExecute(object parameter)
        {

            var ii = (parameter as System.Windows.Controls.WpfPropertyGrid.PropertyItemValue).ParentProperty.Editor;

            if (ii is ICommand)
                return (ii as ICommand).CanExecute(parameter);

            return false;
        }


        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var p = (parameter as System.Windows.Controls.WpfPropertyGrid.PropertyItemValue);
            var ii = p.ParentProperty.Editor;
            try
            {
                (ii as ICommand).Execute(parameter);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(String.Format("Type {0} on {1} throw Exception {2}", ii.GetType(), p, Ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

        }

        private object _commandParameter;
        public object CommandParameter
        {
            get
            {
                return CommandParameter;
            }
            set
            {
                CommandParameter = value;
            }
        }
    }
}
